import 'package:bloc_concurrency/bloc_concurrency.dart';
import 'package:collection/collection.dart';
import 'package:equatable/equatable.dart';
import 'package:excel_utils/pages/daily/daily_data_entry/bean/third_bean.dart';

import 'package:excel_utils/repository/daily_entry/daily_entry_repository.dart';
import 'package:excel_utils/repository/k8/k8_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../bean/CmcTicketBean.dart';
import '../bean/CustomerBean.dart';
import '../bean/DailyInformationBean.dart';
import '../bean/DailyVoteBean.dart';
import '../bean/IndependentStatisticalBean.dart';
import '../bean/LocalDeliveryStatisticsBean.dart';
import '../bean/OtherTopThirtyBean.dart';
import '../bean/SignStatisticsBean.dart';
import '../bean/ThirdPartyBean.dart';

part 'daily_report_event.dart';
part 'daily_report_state.dart';

class DailyReportBloc extends Bloc<DailyReportEvent, DailyReportState> {
  IK8Repository k8Repository;
  IDailyEntryRepository dailyEntryRepository;

  DailyReportBloc(this.k8Repository,this.dailyEntryRepository) : super(DailyReportInitial()) {
    on<DailyReportEvent>((event, emit) {});

    on<DailyReportLocalDeliveryStatisticsDataEvent>((event, emit) async {
      emit(const DailyReportLocalDeliveryStatisticsLoadingState());
      LocalDeliveryStatisticsBean? localDeliveryStatisticsBean = await k8Repository.localDeliveryStatisticsVotingData(maps: {"startTime": event.startDate, "endTime": event.endDate}); // 同城本地表1
      IndependentStatisticalBean? independentStatisticalBean = await k8Repository.independentStatisticalIdentificationData(maps: {"startTime": event.startDate, "endTime": event.endDate}); // 同城本地表 -》電商件入場數細分
      if (localDeliveryStatisticsBean.status == 1 && independentStatisticalBean.status == 1) {
        for (int i = 0; i < localDeliveryStatisticsBean.data!.length; i++) {
          var sCANDATELocalDelivery = localDeliveryStatisticsBean.data?[i].sCANDATE;
          for (var element in independentStatisticalBean.data!) {
            if (sCANDATELocalDelivery == element.dateTime) {
              localDeliveryStatisticsBean.data?[i].oNLINEBUSSINS = element.total; // 电商件入场等雨另一个总和
              double percentage = double.parse(localDeliveryStatisticsBean.data![i].sIGNRATEONLINE.toString().replaceAll('%', '')) / 100;
              double result = percentage * localDeliveryStatisticsBean.data![i].oNLINEBUSSINS!;
              localDeliveryStatisticsBean.data?[i].sIGNONLINE = result.toInt();
              //sIGNONLINE.toString())),  // // 签收
              // sIGNRATEONLINE.toString())),   签收率
              //總件數(入場)  bloc_concurrency
              localDeliveryStatisticsBean.data![i].cOUNTBUSSINS = localDeliveryStatisticsBean.data![i].oNLINEBUSSINS! + localDeliveryStatisticsBean.data![i].lOCALBUSSINS!;
              //簽收(整體)
              double percentage2 = double.parse(localDeliveryStatisticsBean.data![i].sIGNCOUNTONLINE.toString().replaceAll('%', '')) / 100;
              double result2 = percentage2 * localDeliveryStatisticsBean.data![i].cOUNTBUSSINS!;
              localDeliveryStatisticsBean.data![i].sIGNCOUNT = result2.toInt();
            }
          }
        }
      }

      if (localDeliveryStatisticsBean.status == 1) {
        emit(DailyReportLocalDeliveryStatisticsSuccessState(localDeliveryStatisticsBean: localDeliveryStatisticsBean, independentStatisticalBean: independentStatisticalBean));
      } else {
        emit(DailyReportLocalDeliveryStatisticsFailureState(failureMsg: localDeliveryStatisticsBean.msg.toString()));
      }
    }, transformer: sequential());

    // on<IndependentStatisticalIdentificationDataEvent>((event, emit) async {
    //   emit(IndependentStatisticalIdentificationLoadingState());
    //   IndependentStatisticalBean? localDeliveryStatisticsBean =  await  k8Repository.independentStatisticalIdentificationData(maps: {"startTime":event.startDate, "endTime":event.endDate});
    //   if (localDeliveryStatisticsBean.status == 1) {
    //     emit(IndependentStatisticalIdentificationSuccessState(independentStatisticalBean: localDeliveryStatisticsBean));
    //   } else {
    //     emit(DIndependentStatisticalIdentificationFailureState(failureMsg: localDeliveryStatisticsBean.msg.toString()));
    //   }
    // });

    on<OtherTopThirtyDataEvent>((event, emit) async {
      emit(const OtherTopThirtyLoadingState());
      OtherTopThirtyBean? otherTopThirtyBean = await k8Repository.otherTopThirtyData(maps: {"startTime": event.startDate, "endTime": event.endDate});
      if (otherTopThirtyBean.status == 1) {
        emit(OtherTopThirtySuccessState(otherTopThirtyBean: otherTopThirtyBean));
      } else {
        emit(OtherTopThirtyFailureState(failureMsg: otherTopThirtyBean.msg.toString()));
      }
    });

    on<ThirdPartyDataEvent>((event, emit) async {
      emit(const ThirdPartyLoadingState());
      ThirdPartyBean? thirdPartyBean = await k8Repository.thirdPartyData(maps: {"startTime": event.startDate, "endTime": event.endDate});
      try{
        List<ThressData> thirdData =  thirdPartyBean.data??[];
        // 自己处理的第三方数据
        String startDateStr = "${event.startDate.toString().substring(0, 10)}";
        String endDateStr = "${event.endDate.toString().substring(0, 10)}";
        List<ThirdBean> thirds = await dailyEntryRepository.findThirdByDateTime(startDateStr, endDateStr) ?? [];
        for (var value in thirds) {
          // 和 thirdData 的日期对比，如果存在，则更新数据，不存在则新增数据
          if (thirdData.any((element) => element.cREATEDATE == value.createTimeStr)) {
            ThressData third = thirdData.firstWhere((element){
              return element.cREATEDATE.toString() == value.createTimeStr;
            });
            third.skDdc = (value.skDdc=="" || value.skDdc==null)? 0 : int.parse(value.skDdc.toString());
            third.skHvan = (value.skHvan=="" || value.skHvan==null)? 0 : int.parse(value.skHvan.toString());
            third.skBqsjBwb = (value.skBqsjBwb=="" || value.skBqsjBwb==null)? 0 : int.parse(value.skBqsjBwb.toString());
          }
        }
      }catch(e){

      }
      if (thirdPartyBean.status == 1) {
        emit(ThirdPartySuccessState(thirdPartyBean: thirdPartyBean));
      } else {
        emit(ThirdPartyFailureState(failureMsg: thirdPartyBean.msg.toString()));
      }
    });

    on<CmsTicketDataEvent>((event, emit) async {// 报价 负责人  客服  客户地区  联络人  来源 月费套票  报价  后续 数据范围
      emit(const CmsTicketLoadingState());
      CmsTicketBean? cmsBean = await k8Repository.cmsTicketData(maps: {"startTime": event.startDate, "endTime": event.endDate}); // cms票据
      LocalDeliveryStatisticsBean? localDeliveryStatisticsBean = await k8Repository.localDeliveryStatisticsVotingData(maps: {"startTime": event.startDate, "endTime": event.endDate}); // 同城本地表1
      IndependentStatisticalBean? independentStatisticalBean = await k8Repository.independentStatisticalIdentificationData(maps: {"startTime": event.startDate, "endTime": event.endDate}); // 同城本地表 -》電商件入場數細分
      if (localDeliveryStatisticsBean.status == 1 && independentStatisticalBean.status == 1) {
        for (int i = 0; i < localDeliveryStatisticsBean.data!.length; i++) {
          var sCANDATELocalDelivery = localDeliveryStatisticsBean.data?[i].sCANDATE;
          independentStatisticalBean.data!.forEach((element) {
            if (sCANDATELocalDelivery == element.dateTime) {
              localDeliveryStatisticsBean.data?[i].oNLINEBUSSINS = element.total; // 电商件入场等雨另一个总和
              double percentage = double.parse(localDeliveryStatisticsBean.data![i].sIGNRATEONLINE.toString().replaceAll('%', '')) / 100;
              double result = percentage * localDeliveryStatisticsBean.data![i].oNLINEBUSSINS!;
              localDeliveryStatisticsBean.data?[i].sIGNONLINE = result.toInt();
              //sIGNONLINE.toString())),  // // 签收
              // sIGNRATEONLINE.toString())),   签收率
              //總件數(入場)
              localDeliveryStatisticsBean.data![i].cOUNTBUSSINS = localDeliveryStatisticsBean.data![i].oNLINEBUSSINS! + localDeliveryStatisticsBean.data![i].lOCALBUSSINS!;
              //簽收(整體)
              double percentage2 = double.parse(localDeliveryStatisticsBean.data![i].sIGNCOUNTONLINE.toString().replaceAll('%', '')) / 100;
              double result2 = percentage2 * localDeliveryStatisticsBean.data![i].cOUNTBUSSINS!;
              localDeliveryStatisticsBean.data![i].sIGNCOUNT = result2.toInt();
            }
          });
        }
      }
      if (cmsBean.status == 1 && localDeliveryStatisticsBean.status == 1) {
        for (int i = 0; i < cmsBean.data!.length; i++) {
          var cmsData = cmsBean.data![i].gROUPDATE;
          localDeliveryStatisticsBean.data!.forEach((element) {
            if (cmsData == element.sCANDATE) {
              cmsBean.data![i].tCCOUNT = element.lOCALBUSSINS;
              cmsBean.data![i].dSCOUNT = element.oNLINEBUSSINS;
              cmsBean.data![i].aLLCOUNT = cmsBean.data![i].tCCOUNT! + cmsBean.data![i].dSCOUNT!; // F + B
            }
          });
        }
      }

      // 添加指定客户数据
      SignStatisticsBean? signStatistics9821229 = await k8Repository.querySignStatisticsForDataUrl(maps: {"startTime": event.startDate, "endTime": event.endDate, "timeType": "入场时间", "empCode": "9821229"});
      if (signStatistics9821229.status == 1) {
        for (int i = 0; i < cmsBean.data!.length; i++) {
          var cmsData = cmsBean.data![i].gROUPDATE;
          for (var element in signStatistics9821229.data!) {
            if (cmsData == element.gROUPDATE) {
              // 时间相同，替换
              if (element.cOUNT == null || element.cOUNT == 0 || element.cOUNT == 1) {
                cmsBean.data![i].no9821229 = 0;
              } else {
                cmsBean.data![i].no9821229 = element.cOUNT;
              }
            }
          }
        }
      }
      SignStatisticsBean? signStatistics9821190 = await k8Repository.querySignStatisticsForDataUrl(maps: {"startTime": event.startDate, "endTime": event.endDate, "timeType": "入场时间", "empCode": "9821190"});
      if (signStatistics9821190.status == 1) {
        for (int i = 0; i < cmsBean.data!.length; i++) {
          var cmsData = cmsBean.data![i].gROUPDATE;
          for (var element in signStatistics9821190.data!) {
            if (cmsData == element.gROUPDATE) {
              // 时间相同，替换
              if (element.cOUNT == null || element.cOUNT == 0 || element.cOUNT == 1) {
                cmsBean.data![i].no9821190 = 0;
              } else {
                cmsBean.data![i].no9821190 = element.cOUNT;
              }
            }
          }
        }
      }
      if (cmsBean.status == 1) {
        emit(CmsTicketSuccessState(cmsTicketBean: cmsBean));
      } else {
        emit(CmsTicketFailureState(failureMsg: cmsBean.msg.toString()));
      }
    }, transformer: sequential());

    on<SpecifyCustomerEvent>((event, emit) async {
      emit(const SpecifyCustomerLoadingState());
      SignStatisticsBean? signStatistics9821229 = await k8Repository.querySignStatisticsForDataUrl(maps: {"startTime": event.startDate, "endTime": event.endDate, "timeType": "入场时间", "empCode": "9821229"});
      SignStatisticsBean? signStatistics9821190 = await k8Repository.querySignStatisticsForDataUrl(maps: {"startTime": event.startDate, "endTime": event.endDate, "timeType": "入场时间", "empCode": "9821190"});
      List<Map<String, dynamic>> signStatistics = [];
      if (signStatistics9821229.status == 1 && signStatistics9821190.status == 1) {
        int totalCount9821229 = 0;
        signStatistics9821229.data?.forEach((element) {
          totalCount9821229 += element.cOUNT ?? 0;
        });
        signStatistics.add({"label": "9821229", "signStatistics": "$totalCount9821229", "searchDateTime": "${event.startDate}至${event.endDate}"});
        int totalCount9821190 = 0;
        signStatistics9821190.data?.forEach((element) {
          totalCount9821190 += element.cOUNT ?? 0;
        });
        signStatistics.add({"label": "9821190", "signStatistics": "$totalCount9821190", "searchDateTime": "${event.startDate}至${event.endDate}"});
      }
    });

    on<DailyVoteDataEvent>((event, emit) async {
      emit(const DailyVoteLoadingState());
      DailyVoteBean? dailyVoteBean = await k8Repository.dailyVoteData(maps: {"startTime": event.startDate, "endTime": event.endDate});
      if (dailyVoteBean.status == 1) {
        emit(DailyVoteSuccessState(dailyVoteBean: dailyVoteBean));
      } else {
        emit(DailyVoteFailureState(failureMsg: dailyVoteBean.msg.toString()));
      }
    });

    // 运单列印
    on<DailyInformationEvent>((event, emit) =>printingOfWaybill(event: event, emit: emit));

    // 签收统计
    on<SignStatisticsEvent>((event, emit) async {

      return;
      emit(const SignStatisticsLoadingState());
      // 分析日期跨度
      List<Map<String, dynamic>> reqDate = [];
      DateTime startDate = DateTime.parse(event.startDate);
      DateTime endDate = DateTime.parse(event.endDate);
      // 判断两个日期相隔的天数
      int days = endDate.difference(startDate).inDays;
      if(days < 0){
        var startDate15Time = startDate.subtract(const Duration(days: 14));
        String startDate15 = "${startDate15Time.year}-${startDate15Time.month.toString().padLeft(2, '0')}-${(startDate15Time.day).toString().padLeft(2, '0')} 00:00:00";
        reqDate.add({
          "start_date": "${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')} 00:00:00",
          "end_date": "${endDate.year}-${endDate.month.toString().padLeft(2, '0')}-${endDate.day.toString().padLeft(2, '0')} 23:59:59",
          "start_date_15": "${startDate15}",
        });
      }
      for (int i = 0; i <= days; i++) {
        // 开始日期  日期通过 i 累加
        DateTime startOneDayDate = DateTime(startDate.year, startDate.month, startDate.day, 0, 0, 0).add(Duration(days: i));
        // 结束日期
        DateTime endOneDayDate = DateTime(startDate.year, startDate.month, startDate.day, 23, 59, 59).add(Duration(days: i));
        // 15天前
        var startDate15Time = startOneDayDate.subtract(const Duration(days: 14));
        String startDate15 = "${startDate15Time.year}-${startDate15Time.month.toString().padLeft(2, '0')}-${(startDate15Time.day).toString().padLeft(2, '0')} 00:00:00";
        reqDate.add({
          "start_date": "${startOneDayDate.year}-${startOneDayDate.month.toString().padLeft(2, '0')}-${startOneDayDate.day.toString().padLeft(2, '0')} 00:00:00",
          "end_date": "${endOneDayDate.year}-${endOneDayDate.month.toString().padLeft(2, '0')}-${endOneDayDate.day.toString().padLeft(2, '0')} 23:59:59",
          "start_date_15": "${startDate15}",
        });
      }
      List<Map<String, dynamic>> signStatistics = [];
      for (var value in reqDate) {
        String start_date = value["start_date_15"];
        String end_date = value["end_date"];
        SignStatisticsBean? signStatistics98;
        try {
          signStatistics98 = await k8Repository.querySignStatisticsForDataUrl(maps: {"startTime": start_date, "endTime": end_date, "compCode": "98", "timeType": "入场时间"});
        } catch (e) {}
        if (signStatistics98?.status == 1) {
          int totalCount98 = 0;
          int totalCountNotAppearing98 = 0; // 未出场
          int totalCountAlreadyAppearing98 = 0; // 未出场
          signStatistics98?.data?.forEach((element) {
            totalCount98 += element.cOUNT ?? 0;
            if (element.iNCOUNT == null) {
              totalCountNotAppearing98 += 0; // 未出场
            } else {
              totalCountNotAppearing98 += int.parse(element.iNCOUNT.toString().split(" ")[0]);
            }
            if (element.oUTCOUNT == null) {
              totalCountAlreadyAppearing98 += 0; // 已出场
            } else {
              totalCountAlreadyAppearing98 += int.parse(element.oUTCOUNT.toString().split(" ")[0]);
            }
          });
          signStatistics.add({
            "label": "98",
            "signStatistics": "$totalCount98",
            "totalCountNotAppearing98": "$totalCountNotAppearing98",
            "totalCountAlreadyAppearing98": "$totalCountAlreadyAppearing98",
            "searchDateTime": "$start_date  至  $end_date",
            "showDateTime": "${end_date.substring(0, 10)}",
          });
        }
      }
      emit(SignStatisticsSuccessState(signStatistics: signStatistics));
    });
  }

  // 运单列印
  printingOfWaybill({event, emit}) async {
    emit(const DailyInformationLoadingState());
    DailyInformationBean? dailyInformationBean = await k8Repository.dailyInfoData(maps: {"startTime": event.startDate, "endTime": event.endDate, "custType": event.custType});
    DateTime startDate = DateTime.parse(event.startDate);
    DateTime startOneDayDate = DateTime(startDate.year, startDate.month, 1, 0, 0, 0);
    DailyInformationBean? dailyInformationAllBean = await k8Repository.dailyInfoData(maps: {"startTime": "${startOneDayDate.year}-${startOneDayDate.month}-${startOneDayDate.day} 00:00:00", "endTime": event.endDate, "custType": event.custType});
    if (dailyInformationBean.status == 1 && dailyInformationAllBean.status == 1) {
      // 如果客户名称为 . 或者空，则重新查询，改为length的判断
      if (dailyInformationBean.data != null) {
        for (int i = 0; i < dailyInformationBean.data!.length; i++) {
          dynamic value = dailyInformationBean.data![i];
          if (value.cMNAME == "." || value.cMNAME == "") {
            CustomerBean customerBean = await k8Repository.queryCustomerData(maps: {"cmCode": value.cMCODE});
            dailyInformationBean.data![i].cMNAME = "${customerBean.data?.single.cmEname}";
          }
        }
        // dailyInformationBean 进行排序，根据 bGNAME 进行排序
        // dailyInformationBean.data?.sort((a,b){
        //   // 判断是否为英文字符
        //   bool isEnglishA = RegExp(r'^[a-zA-Z]').hasMatch(a.bGNAME.toString());
        //   bool isEnglishB = RegExp(r'^[a-zA-Z]').hasMatch(b.bGNAME.toString());
        //   if (isEnglishA && isEnglishB) {
        //     // 如果都是英文，按照字母顺序排序
        //     return compareAsciiUpperCase(a.bGNAME.toString(), b.bGNAME.toString());
        //   } else if (isEnglishA) {
        //     // 如果a是英文，b是中文，a排在前面
        //     return -1;
        //   } else if (isEnglishB) {
        //     // 如果b是英文，a是中文，b排在前面
        //     return 1;
        //   } else {
        //     // 如果都是中文，按照拼音排序
        //     return a.bGNAME.toString().compareTo(b.bGNAME.toString());
        //   }
        // });
      }
      emit(DailyInformationSuccessState(dailyInformationBean: dailyInformationBean, dailyInformationAllBean: dailyInformationAllBean));
    } else {
      emit(DailyInformationFailureState(failureMsg: dailyInformationBean.msg.toString()));
    }
  }

  // 签收统计
  signInStatistics({event, emit}) async {

  }


}
